package com.cheng.admin.service.order.states;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cheng.admin.constant.Constants;
import com.cheng.admin.dao.OrderMapper;
import com.cheng.admin.service.InviteService;
import com.cheng.common.exception.CustomException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 起凡
 * 订单处于待确认状态
 * 在这个状态下，无法支付，无法取消。
 */
@Order(Constants.ORDER_STATUS_UNCONFIRMED)
@Service
@Slf4j
public class UnconfirmedState implements OrderState {
    @Autowired
    OrderMapper orderMapper;
    @Autowired
    AmqpTemplate amqpTemplate;
    @Autowired
    InviteService inviteService;

    @Override
    public String pay(Long id) {
        throw new CustomException("已支付请勿重复支付");
    }

    @Override
    public Map<String, String> cancel(Long id) {
        throw new CustomException("已支付无法取消订单");
    }

    /**
     * 重新发货，因为快递订单号填错了
     *
     * @param id          订单id
     * @param logisticsNo 物流单号
     * @return
     */
    @Override
    public Map<String, String> ship(Long id, String logisticsNo) {
        orderMapper.update(null, Wrappers.<com.cheng.admin.model.Order>lambdaUpdate()
                .set(com.cheng.admin.model.Order::getLogisticsNo, logisticsNo).eq(com.cheng.admin.model.Order::getId, id));
        HashMap<String, String> result = new HashMap<>();
        result.put("result", "success");
        return result;
    }

    /**
     * 确认订单
     * 在确认订单之后会向邀请者返回一些钱
     * 比如A邀请了B，B支付的了订单且确认之后，A会从B的订单中得到一些抽成。
     * 这个功能是为了奖励拉新用的
     * @param id
     * @return
     */
    @Override
    public Map<String, String> confirm(Long id) {
        com.cheng.admin.model.Order order = orderMapper.selectById(id);
        if (!order.getUserId().equals(StpUtil.getLoginIdAsLong()) && !StpUtil.hasRole("admin")) {
            throw new CustomException("非本人操作");
        }
        orderMapper.update(null, Wrappers.<com.cheng.admin.model.Order>lambdaUpdate()
                .set(com.cheng.admin.model.Order::getCompleteTime, LocalDateTime.now())
                .set(com.cheng.admin.model.Order::getOrderStatus, Constants.ORDER_STATUS_FINISHED).eq(com.cheng.admin.model.Order::getId, id));
        HashMap<String, String> result = new HashMap<>();
        result.put("result", "success");
        //订单抽成
        inviteService.extract(order);
        return result;
    }
}
